﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.TestManagement.Client;

namespace TFSTools.TFSLibrary.TestManagement
{
    public sealed class TFSTestStep : TFSTestAction
    {
        private ITestStep serverTestStep;
        private string title;
        private string expectedResult;

        internal TFSTestStep(TFSTestCase testCase, ITestStep testStep, decimal stepNumber, bool fromSharedStep)
            : base(testCase, testStep, stepNumber)
        {
            this.serverTestStep = testStep;
            this.IsActionFromSharedStep = fromSharedStep;
        }

        public bool IsActionFromSharedStep { get; private set; }

        public override TFSTestActionType ActionType
        {
            get 
            {
                if (this.IsActionFromSharedStep)
                {
                    return TFSTestActionType.SharedStep;
                }
                else
                {
                    return TFSTestActionType.TestStep;
                }
            }
        }

        internal void UpdateSelectedIteration(TFSTestIterationRow iterationData, bool includeParamName, bool includeDelimiter)
        {
            var titleParam = this.serverTestStep.Title;
            var expectedResultParam = this.serverTestStep.ExpectedResult;

            string delimiter = string.Empty;

            if (includeDelimiter)
            {
                delimiter = this.ParameterDelimiter.ToString();
            }

            foreach (var data in iterationData.ReplacementValues)
            {
                string name = data.ParameterName;
                string replacementText = delimiter;
                
                if (includeParamName)
                {
                    replacementText += "@" + name + "=";
                }

                replacementText += data.ReplacementValue + delimiter;
                titleParam = titleParam.ReplaceParameter(name, replacementText);
                expectedResultParam = expectedResultParam.ReplaceParameter(name, replacementText);
            }

            this.title = titleParam;
            this.expectedResult = expectedResultParam;
        }

        public override string Title
        {
            get
            {
                return this.title;
            }
        }

        public override string ExpectedResult
        {
            get
            {
                return this.expectedResult;
            }
        }

        public override string ToString()
        {
            return this.Title + "; " + this.ExpectedResult;
        }
    }
}
